package com.roads.site.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 百度http工具类
 */
public class BaiduHttpUtils {

    /**
     * 百度获取token_url
     */
    private static final String BAIDU_TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token?";

    /**
     * 百度应用URL
     */
    private static final String BAIDU_ID_CARD_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
    /**
     * 百度APP_ID
     */
    private static final String BAIDU_APP_ID = "28114674";
    /**
     * 百度API_KEY
     */
    private static final String BAIDU_API_KEY = "YGCiccVT65XK1zrm5aAoZOyM";
    /**
     * 百度SECRET_KEY
     */
    private static final String BAIDU_SECRET_KEY = "DwdIXa2BUHg1PGY5XF044O4TNUNa7SOk";


    /**
     * 获取授权
     *
     * @return token
     */
    public static String getAuth() throws IOException {
        return getAuth(BAIDU_API_KEY, BAIDU_SECRET_KEY);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Secret Key
     * @return assess_token 示例：
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) throws IOException {
        // 获取token地址
        String getAccessTokenUrl = BAIDU_TOKEN_URL
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        URL realUrl = new URL(getAccessTokenUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        // 获取所有响应头字段
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String result = "";
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        JSONObject jsonObject = JSON.parseObject(result);
        String token = jsonObject.getString("access_token");
        return token;
    }

    public static String idCardFront(String token, byte[] imgData, String detectPhoto) throws Exception {
        String imgStr = Base64Utils.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");
        StringBuilder param = new StringBuilder();
        param.append("id_card_side=front");
        param.append("&image=" + imgParam);
        if ("true".equals(detectPhoto)) {
            param.append("&detect_photo=" + detectPhoto);
        }
        String contentType = "application/x-www-form-urlencoded";
        String encoding = "UTF-8";
        return post(BAIDU_ID_CARD_URL, token, contentType, param.toString(), encoding);
    }

    public static String idCardBank(String token, byte[] imgData) throws Exception {
        String imgStr = Base64Utils.encode(imgData);
        String imgParam = URLEncoder.encode(imgStr, "UTF-8");
        StringBuilder param = new StringBuilder();
        param.append("id_card_side=back");
        param.append("&image=" + imgParam);
        String contentType = "application/x-www-form-urlencoded";
        String encoding = "UTF-8";
        return post(BAIDU_ID_CARD_URL, token, contentType, param.toString(), encoding);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
            throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return postGeneralUrl(url, contentType, params, encoding);
    }

    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
            throws Exception {
        URL url = new URL(generalUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(params.getBytes(encoding));
        out.flush();
        out.close();
        // 建立实际的连接
        connection.connect();
        BufferedReader in = null;
        in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        return result;
    }


}
